<template>
  <div class="user-cards">
    <!-- 页面头部 -->
    <div class="page-header">
      <h2>我的银行卡</h2>
      <p>管理您的银行卡信息，查看余额和交易记录</p>
    </div>

    <!-- 银行卡列表 -->
    <div class="cards-grid">
      <div v-if="cardList.length === 0" class="empty-state">
        <el-empty description="暂无银行卡">
          <el-button type="primary" @click="contactBank">联系银行开户</el-button>
        </el-empty>
      </div>
      
      <div v-else class="card-items">
        <div v-for="card in cardList" :key="card.cardid" class="card-item">
          <div class="bank-card" :class="{ 'card-disabled': card.isreportloss === '是' }">
            <div class="card-header">
              <div class="card-type">
                <span>储蓄卡</span>
                <el-tag :type="getCardStatusType(card.isreportloss)" size="small">
                  {{ card.isreportloss === '否' ? '正常' : '已挂失' }}
                </el-tag>
              </div>
              <div class="card-bank">中国银行</div>
            </div>

            <div class="card-number">
              {{ formatCardNumber(card.cardid) }}
            </div>

            <div class="card-info">
              <div class="balance-info">
                <span class="balance-label">可用余额</span>
                <span class="balance-amount">¥{{ Number(card.balance).toLocaleString() }}</span>
              </div>
              <div class="card-details">
                <span>开户日期：{{ formatDate(card.opendate) }}</span>
                <span>存款类型：{{ getSavingTypeName(card.savingid) }}</span>
              </div>
            </div>

            <div class="card-actions">
              <el-button-group>
                <el-button size="small" @click="refreshBalance(card)" :loading="card.loading">
                  <el-icon><Refresh /></el-icon>
                  刷新余额
                </el-button>
                <el-button size="small" @click="quickDeposit(card)" :disabled="card.isreportloss === '是'">
                  <el-icon><Plus /></el-icon>
                  存款
                </el-button>
                <el-button size="small" @click="quickWithdraw(card)" :disabled="card.isreportloss === '是'">
                  <el-icon><Minus /></el-icon>
                  取款
                </el-button>
                <el-button size="small" @click="quickTransfer(card)" :disabled="card.isreportloss === '是'">
                  <el-icon><Switch /></el-icon>
                  转账
                </el-button>
              </el-button-group>
              
              <el-dropdown @command="(command) => handleCardAction(command, card)">
                <el-button size="small" type="info">
                  更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="changePassword" :disabled="card.isreportloss === '是'">
                      修改密码
                    </el-dropdown-item>
                    <el-dropdown-item command="reportLoss" :disabled="card.isreportloss === '是'" divided>
                      挂失银行卡
                    </el-dropdown-item>
                    <el-dropdown-item command="viewTrades">
                      查看交易记录
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 快捷操作对话框 -->
    <QuickActionDialog
      v-model:visible="quickDialogVisible"
      :action-type="quickActionType"
      :selected-card="selectedCard"
      @success="handleQuickActionSuccess"
    />

    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="passwordDialogVisible"
      title="修改银行卡密码"
      width="400px"
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
      >
        <el-form-item label="银行卡号">
          <el-input :value="selectedCard?.cardid" disabled />
        </el-form-item>
        
        <el-form-item label="当前密码" prop="oldPassword">
          <el-input
            v-model="passwordForm.oldPassword"
            type="password"
            placeholder="请输入当前密码"
            show-password
          />
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="passwordDialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="passwordLoading" @click="handlePasswordChange">
            确认修改
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 挂失确认对话框 -->
    <el-dialog
      v-model="reportLossDialogVisible"
      title="银行卡挂失"
      width="400px"
    >
      <div class="report-loss-content">
        <el-alert
          title="挂失提醒"
          type="warning"
          :closable="false"
          show-icon
        >
          <p>银行卡挂失后将无法进行任何交易操作，请确认是否继续？</p>
        </el-alert>

        <el-form
          ref="reportLossFormRef"
          :model="reportLossForm"
          :rules="reportLossRules"
          label-width="100px"
          style="margin-top: 20px"
        >
          <el-form-item label="银行卡号">
            <el-input :value="selectedCard?.cardid" disabled />
          </el-form-item>

          <el-form-item label="挂失原因" prop="reason">
            <el-select v-model="reportLossForm.reason" placeholder="请选择挂失原因" style="width: 100%">
              <el-option label="银行卡丢失" value="银行卡丢失" />
              <el-option label="银行卡被盗" value="银行卡被盗" />
              <el-option label="密码泄露" value="密码泄露" />
              <el-option label="其他原因" value="其他原因" />
            </el-select>
          </el-form-item>

          <el-form-item label="交易密码" prop="password">
            <el-input
              v-model="reportLossForm.password"
              type="password"
              placeholder="请输入交易密码确认身份"
              show-password
            />
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="reportLossDialogVisible = false">取消</el-button>
          <el-button type="danger" :loading="reportLossLoading" @click="handleReportLoss">
            确认挂失
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Refresh,
  Plus,
  Minus,
  Switch,
  ArrowDown
} from '@element-plus/icons-vue'
import { userApi } from '@/api/user'
import { cardApi } from '@/api/card'
import { adminDepositApi } from '@/api/deposit'
import QuickActionDialog from '@/components/QuickActionDialog.vue'

export default {
  name: 'UserCards',
  components: {
    Refresh,
    Plus,
    Minus,
    Switch,
    ArrowDown,
    QuickActionDialog
  },
  setup() {
    const router = useRouter()
    const store = useStore()
    
    // 数据
    const cardList = ref([])
    const depositTypes = ref([])
    const loading = ref(false)
    
    // 快捷操作
    const quickDialogVisible = ref(false)
    const quickActionType = ref('')
    const selectedCard = ref(null)
    
    // 修改密码
    const passwordDialogVisible = ref(false)
    const passwordLoading = ref(false)
    const passwordFormRef = ref()
    const passwordForm = reactive({
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    })
    
    // 挂失
    const reportLossDialogVisible = ref(false)
    const reportLossLoading = ref(false)
    const reportLossFormRef = ref()
    const reportLossForm = reactive({
      reason: '',
      password: ''
    })

    // 表单验证规则
    const passwordRules = {
      oldPassword: [
        { required: true, message: '请输入当前密码', trigger: 'blur' }
      ],
      newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, message: '密码长度至少6位', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请确认新密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value !== passwordForm.newPassword) {
              callback(new Error('两次输入的密码不一致'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ]
    }

    const reportLossRules = {
      reason: [
        { required: true, message: '请选择挂失原因', trigger: 'change' }
      ],
      password: [
        { required: true, message: '请输入交易密码', trigger: 'blur' }
      ]
    }

    // 获取银行卡列表
    const fetchUserCards = async () => {
      try {
        loading.value = true
        
        const response = await userApi.getUserCards()
        
        if (response && response.code === 0) {
          cardList.value = (response.data || []).map(card => ({
            ...card,
            loading: false
          }))
        } else {
          console.error('获取银行卡失败:', response)
          ElMessage.error(response?.message || '获取银行卡失败')
        }
      } catch (error) {
        console.error('获取银行卡异常:', error)
        // 只有在明确的认证错误时才跳转到登录页
        if (error.response && error.response.status === 401) {
          ElMessage.error('登录已过期，请重新登录')
          store.dispatch('logout')
          router.push('/login')
        } else if (error.message.includes('ECONNREFUSED')) {
          ElMessage.error('无法连接到服务器，请检查网络连接')
        } else {
          ElMessage.error('获取银行卡失败: ' + (error.message || '未知错误'))
        }
      } finally {
        loading.value = false
      }
    }

    // 获取存款类型 - 用户页面不需要获取存款类型，这是管理员功能
    const fetchDepositTypes = async () => {
      // 普通用户不需要获取存款类型列表
      // 存款类型应该由后端在存款时提供选项
      console.log('用户页面不需要获取存款类型')
    }

    // 刷新余额
    const refreshBalance = async (card) => {
      try {
        card.loading = true
        const response = await cardApi.getBalance(card.cardid)
        if (response.code === 0) {
          card.balance = response.data
          ElMessage.success('余额刷新成功')
        }
      } catch (error) {
        console.error('刷新余额失败:', error)
        ElMessage.error('刷新余额失败')
      } finally {
        card.loading = false
      }
    }

    // 快捷操作
    const quickDeposit = (card) => {
      selectedCard.value = card
      quickActionType.value = 'deposit'
      quickDialogVisible.value = true
    }

    const quickWithdraw = (card) => {
      selectedCard.value = card
      quickActionType.value = 'withdraw'
      quickDialogVisible.value = true
    }

    const quickTransfer = (card) => {
      selectedCard.value = card
      quickActionType.value = 'transfer'
      quickDialogVisible.value = true
    }

    // 银行卡操作
    const handleCardAction = (command, card) => {
      selectedCard.value = card
      
      switch (command) {
        case 'changePassword':
          passwordDialogVisible.value = true
          break
        case 'reportLoss':
          reportLossDialogVisible.value = true
          break
        case 'viewTrades':
          router.push({ path: '/user/trades', query: { cardId: card.cardid } })
          break
      }
    }

    // 修改密码
    const handlePasswordChange = async () => {
      if (!passwordFormRef.value) return

      try {
        await passwordFormRef.value.validate()
        passwordLoading.value = true

        const response = await cardApi.changePassword({
          cardid: selectedCard.value.cardid,
          oldPassword: passwordForm.oldPassword,
          newPassword: passwordForm.newPassword
        })

        if (response.code === 0) {
          ElMessage.success('密码修改成功')
          passwordDialogVisible.value = false
          resetPasswordForm()
        } else {
          ElMessage.error(response.message || '密码修改失败')
        }
      } catch (error) {
        console.error('密码修改失败:', error)
        ElMessage.error('密码修改失败')
      } finally {
        passwordLoading.value = false
      }
    }

    // 挂失银行卡
    const handleReportLoss = async () => {
      if (!reportLossFormRef.value) return

      try {
        await reportLossFormRef.value.validate()
        reportLossLoading.value = true

        const response = await cardApi.reportLoss({
          cardid: selectedCard.value.cardid,
          isLoss: '是'
        })

        if (response.code === 0) {
          ElMessage.success('银行卡挂失成功')
          reportLossDialogVisible.value = false
          resetReportLossForm()
          fetchUserCards() // 刷新列表
        } else {
          ElMessage.error(response.message || '挂失失败')
        }
      } catch (error) {
        console.error('挂失失败:', error)
        ElMessage.error('挂失失败')
      } finally {
        reportLossLoading.value = false
      }
    }

    // 快捷操作成功回调
    const handleQuickActionSuccess = () => {
      fetchUserCards()
    }

    // 重置表单
    const resetPasswordForm = () => {
      Object.assign(passwordForm, {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      })
      if (passwordFormRef.value) {
        passwordFormRef.value.resetFields()
      }
    }

    const resetReportLossForm = () => {
      Object.assign(reportLossForm, {
        reason: '',
        password: ''
      })
      if (reportLossFormRef.value) {
        reportLossFormRef.value.resetFields()
      }
    }

    // 工具函数
    const formatCardNumber = (cardNumber) => {
      if (!cardNumber) return ''
      return cardNumber.replace(/(\d{4})(?=\d)/g, '$1 ')
    }

    const formatDate = (date) => {
      if (!date) return ''
      return new Date(date).toLocaleDateString()
    }

    const getCardStatusType = (status) => {
      return status === '否' ? 'success' : 'danger'
    }

    const getSavingTypeName = (savingId) => {
      const type = depositTypes.value.find(t => t.savingid === savingId)
      return type ? type.savingname : '活期'
    }

    const contactBank = () => {
      ElMessageBox.alert(
        '请携带有效身份证件前往银行网点办理开户业务，或拨打客服热线：400-888-8888',
        '开户提醒',
        {
          confirmButtonText: '我知道了',
          type: 'info'
        }
      )
    }

    onMounted(() => {
      fetchUserCards()
      fetchDepositTypes()
    })

    return {
      cardList,
      loading,
      quickDialogVisible,
      quickActionType,
      selectedCard,
      passwordDialogVisible,
      passwordLoading,
      passwordFormRef,
      passwordForm,
      passwordRules,
      reportLossDialogVisible,
      reportLossLoading,
      reportLossFormRef,
      reportLossForm,
      reportLossRules,
      refreshBalance,
      quickDeposit,
      quickWithdraw,
      quickTransfer,
      handleCardAction,
      handlePasswordChange,
      handleReportLoss,
      handleQuickActionSuccess,
      formatCardNumber,
      formatDate,
      getCardStatusType,
      getSavingTypeName,
      contactBank
    }
  }
}
</script>

<style lang="scss" scoped>
.user-cards {
  .page-header {
    margin-bottom: 24px;
    
    h2 {
      margin: 0 0 8px 0;
      color: #303133;
      font-size: 24px;
    }
    
    p {
      margin: 0;
      color: #909399;
      font-size: 14px;
    }
  }

  .cards-grid {
    .empty-state {
      text-align: center;
      padding: 60px 0;
    }

    .card-items {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
      gap: 20px;

      .card-item {
        .bank-card {
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          border-radius: 16px;
          padding: 24px;
          color: white;
          transition: all 0.3s ease;
          position: relative;
          overflow: hidden;

          &::before {
            content: '';
            position: absolute;
            top: -50%;
            right: -50%;
            width: 100%;
            height: 100%;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 50%;
          }

          &.card-disabled {
            background: linear-gradient(135deg, #909399 0%, #606266 100%);
            opacity: 0.7;
          }

          &:hover {
            transform: translateY(-4px);
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
          }

          .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            position: relative;
            z-index: 1;

            .card-type {
              display: flex;
              align-items: center;
              gap: 8px;

              span {
                font-size: 14px;
                opacity: 0.9;
              }
            }

            .card-bank {
              font-weight: 600;
              font-size: 16px;
            }
          }

          .card-number {
            font-size: 20px;
            font-weight: 600;
            letter-spacing: 2px;
            margin-bottom: 20px;
            position: relative;
            z-index: 1;
          }

          .card-info {
            margin-bottom: 20px;
            position: relative;
            z-index: 1;

            .balance-info {
              margin-bottom: 12px;

              .balance-label {
                display: block;
                font-size: 12px;
                opacity: 0.8;
                margin-bottom: 4px;
              }

              .balance-amount {
                font-size: 24px;
                font-weight: bold;
              }
            }

            .card-details {
              display: flex;
              flex-direction: column;
              gap: 4px;

              span {
                font-size: 12px;
                opacity: 0.8;
              }
            }
          }

          .card-actions {
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: relative;
            z-index: 1;

            .el-button-group {
              .el-button {
                background: rgba(255, 255, 255, 0.2);
                border: 1px solid rgba(255, 255, 255, 0.3);
                color: white;
                font-size: 12px;

                &:hover {
                  background: rgba(255, 255, 255, 0.3);
                }

                &:disabled {
                  background: rgba(255, 255, 255, 0.1);
                  opacity: 0.5;
                }
              }
            }

            .el-dropdown {
              .el-button {
                background: rgba(255, 255, 255, 0.2);
                border: 1px solid rgba(255, 255, 255, 0.3);
                color: white;

                &:hover {
                  background: rgba(255, 255, 255, 0.3);
                }
              }
            }
          }
        }
      }
    }
  }

  .dialog-footer {
    text-align: right;
  }

  .report-loss-content {
    .el-alert {
      margin-bottom: 20px;
    }
  }
}

@media (max-width: 768px) {
  .user-cards {
    .cards-grid {
      .card-items {
        grid-template-columns: 1fr;
        gap: 16px;

        .card-item {
          .bank-card {
            .card-actions {
              flex-direction: column;
              gap: 12px;

              .el-button-group {
                width: 100%;

                .el-button {
                  flex: 1;
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>